<template>
  <div class="app-container">
    <div class="filter-container" v-if="userId === 1">
      <!-- 员工ID输入框（可选保留，但默认不显示） -->
      <el-input
        v-model="filterId"
        placeholder="请输入员工ID"
        style="width: 200px; margin-right: 10px;"
        clearable
      ></el-input>
      <!-- 启用员工姓名输入框 -->
      <el-input
        v-model="userName"
        placeholder="请输入员工姓名"
        style="width: 200px; margin-right: 10px;"
        clearable
      ></el-input>
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="loadAttendanceData"
        :loading="loading"
      >查询</el-button>
    </div>

    <el-calendar v-model="currentDate">
      <template slot="dateCell" slot-scope="{date, data}">
        <div
          class="calendar-cell"
          :class="getStatusClass(data.day)"
          @click="showDetail(data.day)"
        >
          <div class="date-number">
            {{ data.day.split('-').slice(2).join('') }}
          </div>
          <div v-if="attendanceRecords[data.day]" class="status-text">
            {{ getStatusText(attendanceRecords[data.day]) }}
          </div>
        </div>
      </template>
    </el-calendar>

    <!-- 处理重名员工的弹窗 -->
    <el-dialog
      title="选择员工"
      :visible.sync="isNameConflictDialogVisible"
      width="30%"
    >
      <el-select v-model="selectedEmployeeId" placeholder="请选择员工">
        <el-option
          v-for="employee in nameConflictEmployees"
          :key="employee.id"
          :label="employee.name"
          :value="employee.id"
        ></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isNameConflictDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEmployeeSelection">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getMonthRecordsById, getMonthRecordsByName, getEmployeesByName } from "@/api/system/records";

  export default {
    name: "RecordsCheck",
    data() {
      return {
        currentDate: new Date(),
        attendanceRecords: {},
        filterId: '',
        userName: '',
        loading: false,
        statusTextMap: {
          NORMAL: '正常',
          LATE: '迟到',
          ABSENT: '缺勤',
          EARLY_LEAVE: '早退' // 添加早退状态
        },
        isNameConflictDialogVisible: false,
        nameConflictEmployees: [],
        selectedEmployeeId: null,
        userId: null // 确保在data中声明userId
      };
    },
    created() {
      this.userId = this.$store.state.user.id;
      this.loadAttendanceData();
    },
    methods: {
      getStatusText(status) {
        return this.statusTextMap[status] || status;
      },

      async loadAttendanceData() {
    this.loading = true;
    try {
      if (this.userId === 1) {
        // 管理员逻辑
        if (this.filterId) {
          const res = await getMonthRecordsById(this.filterId);
          this.processResponse(res);
        } else if (this.userName) {
          const employees = await getEmployeesByName(this.userName);
          if (employees.code === 200 && employees.data.length > 0) {
            if (employees.data.length > 1) {
              this.nameConflictEmployees = employees.data;
              this.isNameConflictDialogVisible = true;
            } else if (employees.data.length === 1) {
              const employee = employees.data[0];
              const employeeId = employee.userId;
              if (employeeId) {
                const res = await getMonthRecordsById(employeeId);
                this.processResponse(res);
              } else {
                this.$message.warning('无法获取员工 ID，无法查询考勤记录');
              }
            }
          } else {
            this.$message.warning('未找到该员工');
          }
        } else {
          const res = await getMonthRecordsById(101); // 管理员默认查询，根据需要调整
          this.processResponse(res);
        }
      } else {
        // 普通用户直接查询自己的考勤
        const res = await getMonthRecordsById(this.userId);
        this.processResponse(res);
      }
    } catch (error) {
      this.$message.error('获取考勤数据失败');
    } finally {
      this.loading = false;
    }
  },

  async confirmEmployeeSelection() {
    if (this.selectedEmployeeId) {
      try {
        const res = await getMonthRecordsById(this.selectedEmployeeId);
        this.processResponse(res);
      } catch (error) {
        this.$message.error('获取考勤数据失败');
      }
    }
    this.isNameConflictDialogVisible = false;
    this.selectedEmployeeId = null;
  },

  processResponse(res) {
    if (res.code === 200) {
      const formattedData = {};
      res.data.forEach(item => {
        if (item.workDate && item.status) {
        const date = new Date(item.workDate);
        const dateStr = this.formatDate(date);
        formattedData[dateStr] = item.status;
      }
    });
      this.attendanceRecords = formattedData;
    } else {
      this.$message.error(res.msg || '获取考勤数据失败');
    }
  },

  getStatusClass(day) {
    const status = this.attendanceRecords[day];
    // return status ? `status-${status.toLowerCase()}` : '';
    return status ? `status-${status.toLowerCase().replace('_', '-')}` : '';
  },

  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  showDetail(day) {
    if (this.attendanceRecords[day]) {
      this.$message.info(`${day}: ${this.getStatusText(this.attendanceRecords[day])}`);
    }
  }
  },
  watch: {
    currentDate: {
      handler() {
        this.loadAttendanceData();
      },
      deep: true
    }
  }
  };
</script>

<style scoped>
.app-container {
  background-color: #f5f7fa;
  padding: 4px;
  border-radius: 8px;
}

.filter-container {
  background-color: white;
  padding: 5px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-calendar {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.calendar-cell {
  height: 80px;
  padding: 8px;
  text-align: center;
  border-radius: 6px;
  font-size: 14px;
  color: #606266;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #ebeef5;
  margin: 2px;
}

.el-calendar-table td.is-selected .calendar-cell {
  border: 2px solid #409eff;
}

.date-number {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
}

.status-text {
  font-size: 12px;
  padding: 2px 5px;
  border-radius: 10px;
  background-color: rgba(255, 255, 255, 0.2);
}

.status-normal {
  background-color: #a0d468 !important;
  color: white !important;
}

.status-late {
  background-color: #ffce54 !important;
  color: white !important;
}

.status-absent {
  background-color: #ed5565 !important;
  color: white !important;
}

.status-early-leave {
  background-color: #ff9b85 !important; /* 早退状态的颜色 */
  color: white !important;
}

.calendar-cell:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-tip {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 16px;
}
.empty-tip i {
  font-size: 40px;
  margin-bottom: 10px;
}
</style>
